#include <windows.h>
#include <stdio.h> 
#include <string>
#include <iostream>
HANDLE hSlot;
LPTSTR up_lpszSlotName = TEXT("\\\\.\\mailslot\\up_mailslot");
void main()
{ 
	DWORD cbMessage, cMessage, cbRead,cAllMessages; 
	BOOL bResult;  
	TCHAR lpszBuffer[1000]; 
	TCHAR achID[80];  
	cbMessage = cMessage = cbRead = 0; 
	hSlot = CreateMailslot(
		up_lpszSlotName,		// mailslot 名
		0,							// 不限制消息大小 
		MAILSLOT_WAIT_FOREVER,         // 无超时 
		NULL); 

	if (hSlot == INVALID_HANDLE_VALUE) 
	{ 
		printf("CreateMailslot failed with %d\n", GetLastError());
		return ; 
	} 
	else 
		printf("Mailslot created successfully.\n"); 

	while(1)
	{
		// 获取mailslot信息
		bResult = GetMailslotInfo(hSlot, // mailslot 句柄 
			(LPDWORD) NULL,               // 无最大消息限制
			&cbMessage,                   // 下一条消息的大小
			&cMessage,                    // 消息的数量
			(LPDWORD) NULL);           // 无时限
		if (!bResult) 
		{ 
			printf("GetMailslotInfo failed with %d.\n", GetLastError()); 
			return ; 
		}  
		printf("MAILSLOT_NO_MESSAGE \n");
		if (cbMessage == MAILSLOT_NO_MESSAGE) 
		{ 
			// 没有消息，过一段时间再去读
			Sleep(3000);
			continue;
		}  
		printf("got MAILSLOT_MESSAGE\n");
		cAllMessages = cMessage; 
		while (cMessage != 0)  // 获取全部消息，有可能不只一条
		{ 
			// 提示信息
			wsprintf(achID, "\nMessage #%d of %d\n", cAllMessages - cMessage + 1, cAllMessages); 			 
			// 读取消息 
			if(!ReadFile(hSlot,lpszBuffer,cbMessage,&cbRead,NULL))
			{ 
				printf("ReadFile failed with %d.\n", GetLastError());  
				return ; 
			}  
			//lstrcat(lpszBuffer, achID); //连接
			printf("Contents of the mailslot: %s\n", lpszBuffer);//显示	

			bResult = GetMailslotInfo(hSlot,NULL,&cbMessage,&cMessage,NULL); // 计算剩余的消息数,若cMessage=0，则退出子循环
			if (!bResult) 
			{ 
				printf("GetMailslotInfo failed (%d)\n", GetLastError());
				return ; 
			}
			
			std::string recvData=std::string(lpszBuffer);
			int pos=recvData.find("__");
			std::string clientAddrStr;
			clientAddrStr=recvData.substr(pos+2);
			std::cout<<"find clientAddr:"<<clientAddrStr<<std::endl;
			
			char timeString[64];
			DWORD cbWritten;
			sprintf_s(timeString,"\\\\.\\mailslot\\down_mailslot_%s",clientAddrStr.c_str());
			LPTSTR down_lpszSlotName = TEXT(timeString);
			HANDLE hFile = CreateFile(down_lpszSlotName, 
				GENERIC_WRITE,		// 可写
				FILE_SHARE_READ,
				(LPSECURITY_ATTRIBUTES) NULL, 
				OPEN_EXISTING,		// 打开一个已经存在的mailslot，应该由服务端已经创建
				FILE_ATTRIBUTE_NORMAL, 
				(HANDLE) NULL); 
			if (hFile == INVALID_HANDLE_VALUE) 
			{ 
				printf("CreateFile failed with %d.\n", GetLastError()); 
				return ; 
			}
			// 向mailslot写入
			char message[100];
			sprintf_s(message,"Hello!Your time is %s",clientAddrStr.c_str());
			LPTSTR lpszMessage=TEXT(message);
			if(!WriteFile(hFile, 
				lpszMessage, 
				(DWORD) (lstrlen(lpszMessage)+1),  
				&cbWritten, 
				(LPOVERLAPPED) NULL)) 
			{ 
				printf("WriteFile failed with %d.\n", GetLastError()); 
				return ; 
			} 
			printf("Slot written to successfully.\n"); 
			CloseHandle(hFile);  // 结束 
		} 
	} 
}